package org.jwap.server.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

public class KeyList<V> {
	
	private List<Key<V>> keys = new ArrayList<Key<V>>();
	
	public void add(Key<V> key){
		keys.add(key);
	}
	
	public void add (String key , V value){
		this.keys.add(new Key<V>(key,value));
	}
	
	public V get(String _key){
		for ( Key<V> key : keys){
			if(key.getKey().equals(_key)){
				return key.getValue();
			}
		}
		return null;
	}
	
	public List<Key<V>> getList(){
		return this.keys;
	}
	
	public void clear(){
		this.keys = new ArrayList<>();
	}
	
	public void remove(Key<V> key){
		this.keys.remove(key);
	}
	
	/*public static KeyList<String> httpPostDataParser(String msg){
		KeyList<String> rValue = new KeyList<>();
		String[] params = msg.split(";");
		for ( String param: params){
			String[] paramParts = param.split("=");
			if ( "name".equals(paramParts[0].trim())){
				if ( subParts.length > 1 ){
					rValue.add(paramParts[1].replace("\"", ""), subParts[1]);
				} else {
					rValue.add(paramParts[1], "");
				}
			}
		}
	}*/
	
	public static KeyList<String> httpGetDataParser(String msg){
		KeyList<String> rValue = new KeyList<>();
		int count = 0;
		String[] pairs = msg.split("&");
		for ( String pair : pairs){
			String[] nameValue = pair.split("=");
			if ( nameValue.length > 1){
				try {
					String key = URLDecoder.decode(nameValue[0], "UTF-8");
					if(key.contains("[]")){
						key = key.replace("[]", "["+count+"]");
						count++;
					}
					rValue.add(key,URLDecoder.decode(nameValue[1],"UTF-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		}
		return rValue;
	}
	
	@Override
	public String toString() {
		StringBuilder out = new StringBuilder();
		for(Key<V> k : keys){
			out.append(k.getKey()+" : "+k.getValue().toString()+" ");
		}
		
		return out.toString();
	}
}
